package com.compass.mobile.ui.activity

import UserInfoManager
import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.activity.viewModels
import androidx.leanback.widget.ArrayObjectAdapter
import androidx.leanback.widget.BaseGridView
import androidx.leanback.widget.FocusHighlight
import androidx.leanback.widget.FocusHighlightHelper
import com.compass.mobile.R
import com.compass.mobile.callback.OnCustomButtonClick
import com.compass.mobile.callback.OnItemClickListener
import com.compass.mobile.callback.OnPhoneDialogClick
import com.compass.mobile.databinding.ActivityPatientsBinding
import com.compass.mobile.framework.base.BaseVBActivity
import com.compass.mobile.framework.constant.ADD_PATIENT
import com.compass.mobile.framework.constant.LOCAL_PHONE
import com.compass.mobile.framework.constant.REFRESH_PATIENT
import com.compass.mobile.framework.constant.YD_USER_TOKEN
import com.compass.mobile.framework.ext.onClick
import com.compass.mobile.framework.utils.DateUtils
import com.compass.mobile.framework.utils.LiveDataBus
import com.compass.mobile.framework.utils.dpToPx
import com.compass.mobile.models.PatientBean
import com.compass.mobile.presenters.PatientPresenter
import com.compass.mobile.ui.dialog.AddInputPhoneDialog
import com.compass.mobile.ui.dialog.AddPatientListDialog
import com.compass.mobile.ui.dialog.AddPatientTipsDialog
import com.compass.mobile.ui.dialog.CodeDialog
import com.compass.mobile.ui.dialog.CommonMessageDialog
import com.compass.mobile.ui.viewModel.UserViewModel
import com.compass.mobile.widget.MyBridgeAdapter
import getStringFromResource
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import toJson

/**
 * Description： 就诊人列表
 * Date:2024/6/12 11:25
 */
class PatientsActivity : BaseVBActivity<ActivityPatientsBinding>() {

    companion object {
        fun start(context: Context) {
            val intent = Intent(context, PatientsActivity::class.java)
            context.startActivity(intent)
        }
    }

    private var randomStr: String? = null
    private lateinit var addInputPhoneDialog: AddInputPhoneDialog.Builder
    private val userViewModel: UserViewModel by viewModels()
    private lateinit var arrayObjectAdapter: ArrayObjectAdapter
    private var patientList: MutableList<PatientBean> = mutableListOf()//包装集合
    @SuppressLint("SetTextI18n")
    override fun initView(savedInstanceState: Bundle?) {
        specialColumn()
        mBinding.topView.setPatientViewVisible(false)
        mBinding.tvLocalPhone.text = "当前登录账号：${UserInfoManager.getString(LOCAL_PHONE)}  (最多可创建10位就诊人)"
    }

    override fun initData() {
        randomStr = "tv${DateUtils.getToday()}"
        showLoading()
        userViewModel.gePatients()
        userViewModel.patientLiveData.observe(this) {
            arrayObjectAdapter.clear()
            it?.let { list ->
                patientList = list
                UserInfoManager.savePatientList(list.toJson())
            }


            if (patientList.size<10){
                patientList.add(PatientBean("10086"))
            }

            arrayObjectAdapter.addAll(0, patientList)
            mBinding.caseItem.requestFocus()
            dismissLoading()
        }
        userViewModel.refreshPatientLiveData.observe(this) {
            dismissLoading()
            LiveDataBus.get().with(REFRESH_PATIENT).postValue(REFRESH_PATIENT)
        }

        userViewModel.addPatientListLiveData.observe(this) {
            dismissLoading()

            if (::addInputPhoneDialog.isInitialized) {
                addInputPhoneDialog.dismissDialog()
            }
            if(it!=null){
                LogUtil.d(it.toJson(), tag = "patientInfo")
            }
            if (!it.isNullOrEmpty()) {
                //检测已经存在则进行同步患者
                showAddPatientListDialog(it)
            } else if(it!=null&& it.size == 0){
                //不存在
                showAddPatientDialog(2)
            }
        }
        userViewModel.checkMobileLiveData.observe(this) {
            it?.let { data ->
                isActive = data != "false"
                if (isActive) {
                    //先调用接口检测是否有就诊人，有的话，则让用户确认 同步、创建
                    //没有验证码的时候传1
                    phoneNumber=data
                    userViewModel.checkMobile(phoneNumber, "", "1")
                }
            } ?: kotlin.run {
                //接口异常后就不再请求了
                isActive = true
            }

        }
        LiveDataBus.get().with(REFRESH_PATIENT, String::class.java)
            .observe(this) {
                showLoading()
                userViewModel.gePatients()
            }
    }

    /**
     * 导入就诊人弹框
     */
    private fun showAddPatientListDialog(patientList: MutableList<PatientBean>) {
        val message = "该手机号存在${patientList.size}位就诊人数据，确定导入吗?"

        val leftStr = "导入"

        val rightStr = "新增"

//        val patientName =
//            patientList.joinToString { "${it.name}  ${it.sex}  年龄：${it.age}" }

        AddPatientListDialog.Builder(this)
            .setTitle("温馨提示")
            .setMessage(message)
            .setPatientList(patientList)
//            .setConfirm(getStringFromResource(R.string.default_confirm))
//            .setCancel(getString(R.string.default_cancel))
            .setConfirm(rightStr)
            .setCancel(leftStr)
            .setonCancelListener {
                it?.dismiss()
                //导入
                showLoading()
                if (code.isNullOrEmpty()){
                    code="8787"
                }
                userViewModel.getMobileSync(phoneNumber, code, "2")
            }
            .setonConfirmListener {
                it?.dismiss()
                //新增
                phoneNumber?.let { it1 -> AddPatientActivity.start(this@PatientsActivity, it1) }

            }.create().show()


    }

    /**
     * 添加就诊人弹框
     */
    private fun showAddPatientDialog(type: Int) {
        val message =
            if (type == 1) "当前手机号已存在就诊人数据，是否导入?" else "是否使用当前手机号添加就诊人？"
        val leftStr =
            if (type == 1) "导入" else "取消"

        val rightStr =
            if (type == 1) "新增" else "确定"
        CommonMessageDialog.Builder(this)
            .setTitle("温馨提示")
            .setMessage(message)
//            .setConfirm(getStringFromResource(R.string.default_confirm))
//            .setCancel(getString(R.string.default_cancel))
            .setConfirm(rightStr)
            .setCancel(leftStr)
            .setonCancelListener {
                it?.dismiss()
                if (type == 1) {
                    //导入
                    showLoading()
                    userViewModel.getMobileSync(phoneNumber, code, "2")

                }

            }
            .setonConfirmListener {
                it?.dismiss()
                if (type == 1) {
                    //新增
                    phoneNumber?.let { it1 -> AddPatientActivity.start(this@PatientsActivity, it1) }
                } else {
                    //新增
                    phoneNumber?.let { it1 -> AddPatientActivity.start(this@PatientsActivity, it1) }
                }

            }.create().show()


    }

    override fun intListener() {
        mBinding.tvRefresh.onClick {
            showLoading()
            userViewModel.gePatients()
        }

    }

    private val onItemClickListener: OnItemClickListener = object : OnItemClickListener {
        override fun onItemClick(position: Int, view: View) {
            val item = patientList[position]
            if (item.id == "10086") {
                cancelInquire()
            } else {
                CommonMessageDialog.Builder(this@PatientsActivity)
                    .setTitle("温馨提示")
                    .setMessage("是否要将当前就诊人解除绑定?")
                    .setConfirm(getStringFromResource(R.string.default_confirm))

                    .setCancel(getString(R.string.default_cancel))
                    .setonCancelListener {
                        it?.dismiss()
                    }
                    .setonConfirmListener {
                        it?.dismiss()
                        showLoading()
                        userViewModel.unbindPatients(item.id)
                    }.create().show()
//                SetPatientDialog.Builder(this@PatientsActivity)
//                    .setonCancelListener {
//                        it?.dismiss()
//                        userViewModel.switchPatients(item.id)
//                    }
//                    .setonConfirmListener {
//                        userViewModel.unbindPatients(item.id)
//                        it?.dismiss()
//                    }.create().show()
            }
        }
    }


    private var onBottomClick: OnCustomButtonClick = object : OnCustomButtonClick {
        override fun onButtonCallBack(codeType: Int, msgType: String?) {
            when (msgType) {
                "local" -> {
//                    showLoading()
//                    userViewModel.getMobileSync("17782523372", "", "1")
                    //跳转至添加页面
                    UserInfoManager.getString(LOCAL_PHONE)?.let {
                        AddPatientActivity.start(this@PatientsActivity, it)
                    } ?: kotlin.run {
                        showToast("本机号码获取失败")
                    }


                }

                "other" -> {
                    useOther()
                }

                "code" -> {
//                    useCode()
//                    AddPatientActivity.start(this@PatientsActivity)
                }
            }
        }
    }


    /**
     * 添加就诊人弹窗
     */
    private fun cancelInquire() {

        UserInfoManager.getString(LOCAL_PHONE)?.let {
            val addPatientTipsDialog =
                AddPatientTipsDialog.Builder(this, it, onBottomClick)
            addPatientTipsDialog.show()
        } ?: kotlin.run {
            showToast("本机号码获取失败")
        }

    }


    private var phoneNumber: String? = null
    private var code: String? = null
    private var onPhoneClick: OnPhoneDialogClick = object : OnPhoneDialogClick {
        override fun onButtonCallBack(codeType: Int, phone: String?, msgType: String?) {
            when (codeType) {
                1 -> {
                    phoneNumber = phone
                    if (phoneNumber.isNullOrEmpty()) {
                        showToast("请输入手机号码")
                        return
                    }
                    userViewModel.getCode(phoneNumber)

                }

                2 -> {
//                    code = msgType
//                    if (code.isNullOrEmpty()) {
//                        showToast("请输入验证码")
//                        return
//                    }
                    phoneNumber = phone
                    showLoading()
                    //先调用接口检测是否有就诊人，有的话，则让用户确认 同步、创建
                    userViewModel.checkMobile(phone, msgType, "2")
//                    showLoading()
//                    userViewModel.getMobileSync(phoneNumber, code, "2")
                }
            }
        }
    }

    private fun useOther() {
        isActive = false
        phoneNumber=null
        startPolling(1500)
        addInputPhoneDialog =
            AddInputPhoneDialog.Builder(this@PatientsActivity, onPhoneClick, randomStr)
        addInputPhoneDialog.show()
    }

    private var isActive: Boolean = false
    private fun startPolling(intervalMillis: Long) {
        CoroutineScope(Dispatchers.IO).launch {
            while (!isActive) {
                userViewModel.checkPatient(randomStr)
                delay(intervalMillis) // 暂停一段时间，以轮询间隔继续
            }
        }
    }

    /**
     * 使用扫码
     */
    private fun useCode() {
        val oderCodeDialog = CodeDialog.Builder(
            this@PatientsActivity,
            ADD_PATIENT
        )
        oderCodeDialog.show()
    }

    @SuppressLint("RestrictedApi")
    fun specialColumn() {
        mBinding.caseItem.horizontalSpacing = dpToPx(10)
        arrayObjectAdapter = ArrayObjectAdapter(PatientPresenter())
        val itemBridgeAdapter = MyBridgeAdapter(
            this,
            arrayObjectAdapter, onItemClickListener
        )
        mBinding.caseItem.setAdapter(itemBridgeAdapter)
        mBinding.caseItem.setFocusScrollStrategy(BaseGridView.FOCUS_SCROLL_ITEM)
        arrayObjectAdapter.addAll(0, patientList)

        FocusHighlightHelper.setupBrowseItemFocusHighlight(
            itemBridgeAdapter,
            FocusHighlight.ZOOM_FACTOR_NONE, false
        )


    }
}
